package cn.learn.hystrix.service;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

/**
 * 服务降级的demo
 * 超时，运行时异常
 * 都会走 兜底  方案
 *
 * @author huangyezhan
 * @version 1.0
 * @date 2020年11月28日8:18
 */
@Service
@DefaultProperties(defaultFallback = "globalHystrixHandler")
public class HystrixService {

    public String hystrixOk(Integer id) {
        return Thread.currentThread().getName() + ":  O(∩_∩)O 非常健康" + id;
    }


    /**
     * 自定义的服务降级
     */
    @HystrixCommand(fallbackMethod = "hystrixTimeOutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public String hystrixTimeOut(Integer id) {
        //int a = 10 /0;
        System.out.println(Thread.currentThread().getName() + "  id:" + id);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Thread.currentThread().getName() + ":   O(∩_∩)O 非常健康" + id;
    }

    /**
     * 走全局的服务降级，不指定特殊属性，默认走全局的
     */
    @HystrixCommand
    public String hystrixGlobal(Integer id) {
        int a = 10 / 0;
        return Thread.currentThread().getName() + ":  O(∩_∩)O 非常健康" + id;
    }

    public String hystrixTimeOutHandler(Integer id) {
        return Thread.currentThread().getName() + ":   ┭┮﹏┭┮" + "  超时了！" + id;
    }

    /**
     * 全局的服务降级
     * 全局的不能带参数
     */
    public String globalHystrixHandler() {
        return "global全局服务降级了！";
    }


    /**
     * 服务熔断
     */
    @HystrixCommand(fallbackMethod = "hystrixTimeOutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"),

            @HystrixProperty(name = "circuitBreaker.enable",value = "true"),                    //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),      //请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")     //失败率达到多少后跳闸
    })
    public String hystrixBreak(Integer id) {
        //int a = 10 /0;
        System.out.println(Thread.currentThread().getName() + "  id:" + id);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Thread.currentThread().getName() + ":   O(∩_∩)O 非常健康" + id;
    }

}
